package com.hjs.servlet.regularinspection.pavementflatness;

import com.hjs.bean.PavementFlatness;
import com.hjs.bean.RegularInspection;
import com.hjs.mapper.RegularInspectionMapper;
import com.hjs.tools.EvaluationUtil;
import com.hjs.tools.Mapper;
import com.hjs.tools.RequestUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/PavementFlatness/add")
@Slf4j
public class AddPavementFlatness extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
        /*
         * 提供参数
         * userID
         * IRI
         * regularInspectionID
         * flatnessDate
         * remarks（可选）
         */
        RequestUtil requestUtil = new RequestUtil(request, response);
        try (SqlSession sqlSession = Mapper.getSqlSession()) {
            RegularInspectionMapper regularInspectionMapper = sqlSession.getMapper(RegularInspectionMapper.class);
            RegularInspection regularInspection = regularInspectionMapper.getOneRegularInspectionById(requestUtil.getInt("regularInspectionID"));
            PavementFlatness pavementFlatness = new PavementFlatness(null,requestUtil.getDateTime("flatnessDate"),
                    requestUtil.getString("userID"), requestUtil.getDouble("IRI"),
                    requestUtil.getString("remarks"), regularInspection.getRegularInspectionID());
            boolean sqlResult = regularInspectionMapper.addOnePavementFlatness(pavementFlatness);
            if(sqlResult) {
                sqlResult = regularInspectionMapper.updateFlatnessIDRegularInspectionById(regularInspection.getRegularInspectionID(),
                        pavementFlatness.getFlatnessID());
                if (sqlResult && regularInspection.getPavementDamageComID() != null) {
                    sqlResult = EvaluationUtil.evaluationResult(requestUtil,sqlSession,1);
                }
            }
            Mapper.SessionEnd(sqlResult, sqlSession,"添加路面损坏情况失败");
            requestUtil.responseIsSuccess(sqlResult,"添加路面损坏情况失败");
        } catch (Exception e) {
            log.error(e.toString());
            requestUtil.responseFail("未知错误");
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) {
        doPost(request, response);
    }


}
